/**
 * 酒秀
 * 9elephas.com
 */

import React, { Component } from 'react'
import {
  StyleSheet, View, Text, Alert, InteractionManager,
  StatusBar, Platform, TouchableOpacity, Image
} from 'react-native'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { NavigationActions } from 'react-navigation'
import { COLOR, STATUS_BAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT } from '../config'
import * as utils from '../utils'
import { navToBootstrap, navToTab } from '../navigation'
import * as components from './'
import * as actions from '../actions'

class Bootstrap extends Component {
  constructor(props) {
    super(props)

    this.screenId = props.screenId || 'Bootstrap'
    this.state = {
      token: true
    }
  }



  componentDidMount() {
    this.start()
  }


  //如果再次检测网络成功,那么清空路由
  input() {
    resetAction = NavigationActions.reset({
      index: 0,
      actions: [
        NavigationActions.navigate({ routeName: 'Bootstrap' })//要跳转到的页面名字
      ]
    });
    this.props.navigation.dispatch(resetAction);
  }

  start() {
    InteractionManager.runAfterInteractions(() => {
      let { navigation, reset, processingTask, errorFlash,
        isLogined } = this.props
      let { isReset } = navigation.state.params || {}

      if (isReset) {
        reset()
      }

      let cbLogined = user => {
        if (user.nickname && user.avatarType && user.gender) {
          navToTab(navigation)
        } else {
          navigation.navigate('RegisterProfile')
        }
      }

      processingTask('正在检测网络和获取位置')
      utils.waitingFor({
        condition: () => {
          let { persist, network } = this.props
          return network.isConnected && persist.rehydrated
        },
        cbOk: () => {
          processingTask('')
          isLogined({
            cbOk: ({ user, settings }) => {
              if (user) {
                cbLogined(user)
              } else {
                navigation.navigate('PreLogin')
              }
            },
            cbFail: error => {
              console.log(error + '~~~~~~~~~~~~~~~~~~~启动的错误')
              Alert.alert(
                '启动出错',
                error.message,
                [
                  { text: '重试', onPress: () => navToBootstrap(navigation) },
                  { text: '进入', onPress: () => navigation.navigate('Home') }
                ]
              )
            }
          })
          // if (this.state.token) {
          //   navigation.navigate('PreLogin')
          // }else{
          //   navigation.navigate('Home')
          // }
        },
        cbFail: () => {
          processingTask('')
          Alert.alert(
            '网络出错',
            '未检测到网络连接，请确保WIFI或移动网络正常可用。',
            [
              {
                text: '重试',
                onPress: () => this.input()
              },
              // {
              //   text: '离线模式',
              //   onPress: () => {
              //     let {object, account} = this.props
              //     let user = object.users[account.id]
              //     if (user) {
              //       cbLogined(user)
              //     } else {
              //       errorFlash('尚未登录过任何帐号。')
              //       navToBootstrap(navigation)
              //     }
              //   }
              // }
            ]
          )
        },
        maxTimes: 5
      })
    })
  }

  render() {
    return (
      // <components.Layout
      //   screenId={this.screenId}
      //   containerStyle={{
      //     marginTop: (Platform.OS === 'ios' ? STATUS_BAR_HEIGHT : 0)
      //   }}
      // >
      //   <StatusBar barStyle='dark-content' />
      //   <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
      //     <components.Image
      //       source={require('../image/one.png')}
      //       style={{borderRadius: 30}}
      //     />
      //     <Text style={styles.title}>酒秀11111</Text>
      //   </View>
      // </components.Layout>
      <components.Layout
        screenId={this.screenId}
        containerStyle={{
          marginTop: (Platform.OS === 'ios' ? STATUS_BAR_HEIGHT : 0)
        }}
      >


        <View style={{ width: SCREEN_WIDTH, height: SCREEN_HEIGHT }}>
          <TouchableOpacity style={{ width: SCREEN_WIDTH, height: SCREEN_HEIGHT }}
            onPress={() => this.start()}
          >
            {
              Platform.OS === 'ios' ?
                <Image source={{ uri: '4.png' }} style={{ width: SCREEN_WIDTH, height: SCREEN_HEIGHT }} />
                :
                <Image source={{ uri: 'gui4' }} style={{ width: SCREEN_WIDTH, height: SCREEN_HEIGHT }} />
            }

          </TouchableOpacity>
        </View>



      </components.Layout>
    )
  }
}

const styles = StyleSheet.create({
  title: {
    marginTop: 50,
    fontSize: 32,
    color: COLOR.textEmpha
  }
})

function mapStateToProps(state) {
  let { persist, network, object, account } = state
  return {
    persist,
    network,
    object,
    account
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actions, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(Bootstrap)
